package aar.test.tessocr;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.CustomFooterViewCallBack;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.greenrobot.eventbus.EventBus;
import org.opencv.android.OpenCVLoader;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import aar.test.tessocr.EventMessage.EventMessage;
import aar.test.tessocr.adapter.CabinetListAdapter;
import aar.test.tessocr.adapter.interfaces.OnItemClickListener;
import aar.test.tessocr.base.BaseActivity;
import aar.test.tessocr.baseApplication.BaseApplication;
import aar.test.tessocr.model.CabinetListMpdel;
import aar.test.tessocr.model.DialogCallback;
import aar.test.tessocr.model.LoginCabModel;
import aar.test.tessocr.model.LzyResponse;
import aar.test.tessocr.model.loginModel;
import aar.test.tessocr.tessOcrUtil.TesseractUtil;
import aar.test.tessocr.utils.ConstantPara;
import aar.test.tessocr.utils.LogUtils;
import aar.test.tessocr.utils.PrefUtils;
import aar.test.tessocr.utils.UnzipAssets;
import aar.test.tessocr.utils.Urls;
import aar.test.tessocr.view.CustomLoadingMoreFooter;
import butterknife.BindView;
import clx.tessocr.ocreng.R;
import lib_zxing.activity.CaptureActivity;
import lib_zxing.activity.CaptureFragment;
import lib_zxing.activity.CodeUtils;
import okgo.OkGo;
import okgo.model.Response;
import okhttp3.RequestBody;

import static aar.test.tessocr.Login1Activity.JSON;
import static aar.test.tessocr.MainActivity.APP_KEY;

public class ScanLoginCabActivity extends BaseActivity implements XRecyclerView.LoadingListener{

    private Context mContext;

    private DisplayMetrics dm;

    private LinearLayout left_layout;

    private TextView title_info;

    private TextView scan_open_cab;


    private String text;

    private FrameLayout fl_zxing_container;


    private EditText san_order_id;
    private String from = "";
    XRecyclerView rvData;
    TextView tv_no_data;

    private List<CabinetListMpdel> mList = new ArrayList<>();
    private CabinetListAdapter mAdapter;
    private boolean isFirst = true;
    private int pageNum = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        from = getIntent().getStringExtra("from");
        mContext = this;
        setContentView(R.layout.activity_scan_login_cab_old);
        initView();

        dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);

        iniLoadOpenCV();


        if (Build.VERSION.SDK_INT >= 23) {
            requestP();

        } else {

            unZipAssset();
        }


    }

    private void iniLoadOpenCV() {
        boolean success = OpenCVLoader.initDebug();
        if (success) {
            Log.e("MainActivity", "OpenCV Library loaded...");
        } else {
            Toast.makeText(this.getApplicationContext(), "could not load opencv lib...", Toast.LENGTH_SHORT).show();
        }
    }


    private void unZipAssset() {

        prepareSdPath();

        prepareSdPath2();

        try {

            File file = new File(TesseractUtil.TESSBASE_PATH_DOWN);

            File file2 = new File(TesseractUtil.TESSBASE_PATH_DOWN + "/eng.traineddata");

            if (!file.exists() || (file.exists() && !file2.exists())) {
                new Thread() {
                    public void run() {
                        //在新线程中以同名覆盖方式解压
                        UnzipAssets.unZip(ScanLoginCabActivity.this, ConstantPara.UN_ZIP_ASSET_NAME, TesseractUtil.TESSBASE_PATH, true);
                    }
                }.start();

            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    //准备sd卡存储路径用来存储视频和图片
    private void prepareSdPath() {

        try {

            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                File sPathRootThumbnail = new File(TesseractUtil.TESSBASE_PATH);
                if (!sPathRootThumbnail.exists()) {
                    sPathRootThumbnail.mkdirs();
                }

            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    //准备sd卡存储路径用来存储视频和图片
    private void prepareSdPath2() {

        String RootFilePath = Environment.getExternalStorageDirectory() + "/DCIM/";

        String sSubDir = "normal";
//        String RootFilePath=  Environment.getExternalStorageDirectory() + "/Download/";

        try {


            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                File sPathRoot = new File(RootFilePath);
                if (!sPathRoot.exists()) {
                    sPathRoot.mkdirs();
                }
                File sPathVid = new File(RootFilePath + sSubDir);
                LogUtils.e("MainActivity", "sPathVid.exists()==" + sPathVid.exists());
                if (!sPathVid.exists()) {
                    sPathVid.mkdirs();
                }

            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void initView() {
        rvData = findViewById(R.id.rv_data);
        tv_no_data = findViewById(R.id.tv_no_data);
        LinearLayoutManager manager = new LinearLayoutManager(ScanLoginCabActivity.this);
        rvData.setLayoutManager(manager);
        mAdapter = new CabinetListAdapter(ScanLoginCabActivity.this, mList, true);
        rvData.setAdapter(mAdapter);
        final CustomLoadingMoreFooter footer = new CustomLoadingMoreFooter(ScanLoginCabActivity.this);
        rvData.setFootView(footer, new CustomFooterViewCallBack() {
            @Override
            public void onLoadingMore(View yourFooterView) {
                footer.onLoadingMore();
            }

            @Override
            public void onLoadMoreComplete(View yourFooterView) {
                footer.onLoadMoreComplete();
            }

            @Override
            public void onSetNoMore(View yourFooterView, boolean noMore) {
                footer.onSetNoMore();
            }
        });
        rvData.setPullRefreshEnabled(true);
        rvData.setLoadingMoreEnabled(true);
        rvData.setLoadingListener(ScanLoginCabActivity.this);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                san_order_id.setText(mList.get(position).getCabinetCode());
                scanOpenCab();
            }

            @Override
            public void onItemClick(String date, int weekday) {
            }
        });

        CaptureFragment captureFragment =  CaptureFragment.newInstance(2);
        captureFragment.setAnalyzeCallback(analyzeCallback);
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_zxing_container, captureFragment).commit();
        captureFragment.setCameraInitCallBack(new CaptureFragment.CameraInitCallBack() {
            @Override
            public void callBack(Exception e) {
                if (e == null) {

                } else {
                    Log.e("TAG", "callBack: ", e);
                }
            }
        });


        left_layout = findViewById(R.id.left_layout);
        left_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                faaa();

            }
        });

        fl_zxing_container = findViewById(R.id.fl_zxing_container);


        san_order_id = findViewById(R.id.san_order_id);

        scan_open_cab = findViewById(R.id.scan_open_cab);
        scan_open_cab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scanOpenCab();
            }
        });


    }


    private void requestP() {

        AndPermission.with(this)
                .requestCode(ConstantPara.REQUEST_CODE_PERMISSION_SD)
                .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .callback(permissionListener)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(mContext, rationale).
                                show();
                    }
                })
                .start();
    }


    /**
     * 回调监听。
     */
    private PermissionListener permissionListener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            switch (requestCode) {
                case ConstantPara.REQUEST_CODE_PERMISSION_SD: {
//                    Toast.makeText(MainActivity.this, "111111111111", Toast.LENGTH_SHORT).show();
                    unZipAssset();
                    break;
                }

            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            switch (requestCode) {
                case ConstantPara.REQUEST_CODE_PERMISSION_SD: {
//                    Toast.makeText(ShowMobleSDMediaActivity.this, R.string.message_post_failed, Toast.LENGTH_SHORT).show();
                    break;
                }

            }


            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(ScanLoginCabActivity.this, deniedPermissions)) {

                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(ScanLoginCabActivity.this, ConstantPara.REQUEST_CODE_SETTING, dm).show();

                // 第二种：用自定义的提示语。
//             AndPermission.defaultSettingDialog(this, REQUEST_CODE_SETTING)
//                     .setTitle("权限申请失败")
//                     .setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权，否则功能无法正常使用！")
//                     .setPositiveButton("好，去设置")
//                     .show();

            }
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();

        OkGo.getInstance().cancelTag(this);
    }


    /**
     * 二维码解析回调函数
     */
    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result, final int type) {

//            if (type == 1) {
//                Toast.makeText(AppointmentOrderActivity.this, "bar      " + result, Toast.LENGTH_LONG).show();
//            } else if (type == 2) {
//                Toast.makeText(AppointmentOrderActivity.this, "phone       " + result, Toast.LENGTH_LONG).show();
//            }

            final String res = result;
            if (!TextUtils.isEmpty(res)) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        if (type == 1) {
                            san_order_id.setText(res.trim().substring(res.trim().lastIndexOf("?") + 1));
                            scanOpenCab();
                        } else if (type == 2) {


                        }


                    }
                });
            }


        }

        @Override
        public void onAnalyzeFailed() {

            Toast.makeText(ScanLoginCabActivity.this, "没有识别到信息", Toast.LENGTH_SHORT).show();
        }
    };


    private void scanOpenCab() {


        String mm = san_order_id.getText().toString();

        if (TextUtils.isEmpty(mm)) {
            Toast.makeText(mContext, "没有柜子编号，请扫描", Toast.LENGTH_SHORT).show();
            return;
        }

        Map<String, Object> map = new HashMap<>();

        map.put("cabinetCode", mm);
        map.put("adminid", PrefUtils.getString(this, "userId", ""));


        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON,json);
        OkGo.<LzyResponse<LoginCabModel>>post(Urls.URL_LOGIN_CAB)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse<LoginCabModel>>(ScanLoginCabActivity.this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<LoginCabModel>> response) {
                        if(null!= response.body().msg){
                            Toast.makeText(ScanLoginCabActivity.this, response.body().msg, Toast.LENGTH_SHORT).show();
                            Log.e("MainActivity", "onSuccess-----URL_OPENGRID---------------" + response.body().data);

                            PrefUtils.setString(ScanLoginCabActivity.this, "cabinetCode", response.body().data.getCabinetcode());
                            PrefUtils.setBoolean(ScanLoginCabActivity.this, "cabinetLoginFlag", true);
                            PrefUtils.setString(ScanLoginCabActivity.this, "cabinetId", response.body().data.getCabinetid());
                        }
                        if(null!=response.body().data){
                            BaseApplication.getIntance().setLoginCabModel(response.body().data);
                        }

                        if (from.equals("isFromLogin")) {
                            mm();
                        } else if (from.equals("isFromQuick")) {
                            mm();
                            /*EventBus.getDefault().post(new EventMessage().setMessage("LoginCabSuccess"));
                            Intent intent = new Intent(ScanLoginCabActivity.this, SiteDispatchNewActivity.class);
                            intent.putExtra(MainActivity.EXTRA_KEY_APP_KEY, APP_KEY);
                            startActivity(intent);
                            finish();*/
                        } else if (from.equals("isFromAppointment")) {
                            /*EventBus.getDefault().post(new EventMessage().setMessage("LoginCabSuccess"));
                            Intent intent1 = new Intent(ScanLoginCabActivity.this, OpenCabActivity.class);
                            // 合合信息授权提供的APP_KEY
                            intent1.putExtra(MainActivity.EXTRA_KEY_APP_KEY, APP_KEY);
                            startActivity(intent1);
                            finish();*/
                            mm();
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<LoginCabModel>> response) {
                        faaa();

                    }
                });




    }


    private void mm() {

        Intent resultIntent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_SUCCESS);
        resultIntent.putExtras(bundle);
        setResult(RESULT_OK, resultIntent);
        finish();
    }


    private void faaa() {

        Intent resultIntent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_FAILED);
        resultIntent.putExtras(bundle);
        setResult(RESULT_OK, resultIntent);
        finish();
    }


    @Override
    public void onRefresh() {
        pageNum = 1;
        getData();
    }

    @Override
    public void onLoadMore() {
        getData();
    }

    @Override
    public void onResume() {
        super.onResume();

        if (isFirst) {
            isFirst = false;
            refreshData();
        }
    }

    private void refreshData() {
        pageNum = 1;
        getData();
    }

    private void getData() {
        Map<String, Object> map = new HashMap<>();
        map.put("adminid", PrefUtils.getString(ScanLoginCabActivity.this, "userId", ""));
        map.put("page", pageNum);
        map.put("size", ConstantPara.PAGESIZE);
        map.put("keyword", "");

        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<LzyResponse<List<CabinetListMpdel>>>post(Urls.URL_CAB_LIST)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse<List<CabinetListMpdel>>>(ScanLoginCabActivity.this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<List<CabinetListMpdel>>> response) {
                        if (pageNum == 1) {
                            mList.clear();
                        }

                        if (null != response.body().data) {
                            mList.addAll(response.body().data);
                        }

                        if (null == mList || mList.size() == 0) {
                            tv_no_data.setVisibility(View.VISIBLE);
                        } else {
                            tv_no_data.setVisibility(View.GONE);
                        }

                        if (null == response.body().data || response.body().data.size() == 0) {
                            mAdapter.notifyDataSetChanged();

                            rvData.refreshComplete();
                            rvData.loadMoreComplete();
                            rvData.setNoMore(true);
                        } else {
                            if (null != response.body().data && response.body().data.size() > 0) {
                                rvData.refreshComplete();
                                pageNum++;
                                mAdapter.notifyDataSetChanged();
                            }
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<List<CabinetListMpdel>>> response) {
                        if (pageNum == 1) {
                            tv_no_data.setVisibility(View.VISIBLE);
                            mList.clear();
                            mAdapter.notifyDataSetChanged();
                        }
                        rvData.refreshComplete();
                        rvData.loadMoreComplete();
                        rvData.setNoMore(true);
                    }
                });
    }
}
